﻿namespace EFS.Common.UI.Controls.NotificationDialog
{
	/// <summary>
	/// A Silverlight implementation of IModalDialogHost
	/// </summary>
	public partial class ProgressModal : EFS.Common.UI.Controls.ChildWindow
	{
		#region Composition

		// messages
		System.Collections.Generic.Dictionary<System.Object, EFS.Common.UI.Controls.NotificationDialog.ProgressMessage>
			messages = new System.Collections.Generic.Dictionary<System.Object, EFS.Common.UI.Controls.NotificationDialog.ProgressMessage>();

		#endregion

		#region Delegates
		/// <summary>
		/// AllCompleted
		/// </summary>
		public delegate void AllCompleted();
		public AllCompleted OnAllCompleted;

		#endregion

		/// <summary>
		/// Constructor
		/// </summary>
		public ProgressModal()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Cancel all
		/// </summary>
		public void CancelAll()
		{
			// clear
			messages.Clear();

			// close
			CloseWhenAllCompleted();
		}

		/// <summary>
		/// Append
		/// </summary>
		/// <param name="message"></param>
		public void Append(System.Object key, System.String text)
		{
			// remove if already in
			if (messages.ContainsKey(key))
			{
				messages.Remove(key);
			}

			// add
			messages.Add(key, new EFS.Common.UI.Controls.NotificationDialog.ProgressMessage() { Text = text, Status = PorgressStatus.InProgress });

			// set source
			dataGridMessages.ItemsSource = messages.Values;
		}

		/// <summary>
		/// Append
		/// </summary>
		/// <param name="message"></param>
		public void Completed(System.Object key)
		{
			// check
			if (messages.ContainsKey(key))
			{
				// add
				messages[key].Status = PorgressStatus.Completed;

				// clean
				dataGridMessages.ItemsSource = null;

				// set source
				dataGridMessages.ItemsSource = messages.Values;
			}

			// close
			CloseWhenAllCompleted();
		}

		/// <summary>
		/// Close if all completed
		/// </summary>
		private void CloseWhenAllCompleted()
		{
			// check all
			foreach (EFS.Common.UI.Controls.NotificationDialog.ProgressMessage progressMessage in messages.Values)
			{
				if (progressMessage.Status == PorgressStatus.InProgress)
				{
					return;
				}
			}

			// clear
			messages.Clear();
			dataGridMessages.ItemsSource = null;

			// close
			Close();
		}
	}
}